<template>
  <div>
    <el-card>
      <!-- 柱状图 -->
      <v-chart :options="barOptions"></v-chart>
    </el-card>
    <el-card>
      <!-- 折线图 -->
      <v-chart :options="lineOptions"></v-chart>
    </el-card>
  </div>
</template>

<script>
// 导入vue-echarts
import vueEcharts from "vue-echarts";
// 按需导入绘制对应图表的工具包
import "echarts/lib/chart/line";
import "echarts/lib/chart/bar";
// 导入提示工具包
import "echarts/lib/component/tooltip";
import "echarts/lib/component/toolbox";

export default {
  components: {
    "v-chart": vueEcharts
  },
  data() {
    return {
      // 销售业绩
      saleData: [],
      // x轴
      xData: [],
      // y轴
      yData: [],
      // 柱状图的配置对象
      barOptions: {
        title: {
          text: "月度销售业绩柱状图"
        },
        tooltip: {},
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: "none"
            },
            restore: {},
            saveAsImage: {}
          }
        },
        legend: {},
        xAxis: {
          type: "category"
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            type: "bar", // 指定图表的形状
            showBackground: true,
            backgroundStyle: {
              color: "rgba(220, 220, 220, 0.8)"
            }
          }
        ]
      },
      lineOptions: {
        title: {
          text: "月度销售业绩折线图"
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: "none"
            },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          boundaryGap: false
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            data: [],
            type: "line", // 指定图表的形状
            areaStyle: {}
          }
        ]
      }
    };
  },
  methods: {
    async queryData() {
      const res = await this.$http.get("/api/charts");
      if (res.code == 200) {
        this.saleData = res.list;
        this.saleData.forEach(item => {
          // x轴
          this.xData.push(item.month + "月");
          // y轴
          this.yData.push(item.total);
        });
        // 更新this.barOptions
        this.barOptions = Object.assign(this.barOptions, {
          xAxis: { data: this.xData },
          series: { data: this.yData }
        });
        this.lineOptions = Object.assign(this.lineOptions, {
          xAxis: { data: this.xData },
          series: { data: this.yData }
        });
      }
    }
  },
  created() {
    this.queryData();
  }
};
</script>

<style>
.echarts {
  width: 100% !important;
  height: 400px !important;
}
</style>